package com.fjwt.gz.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.db.dto.ActivityAwardDTO;
import com.fjwt.gz.db.dto.AwardGoodsDTO;
import com.fjwt.gz.db.dto.PointDTO;
import com.fjwt.gz.db.entity.ActivityAwardEntity;
import com.fjwt.gz.db.entity.AgentInfoEntity;
import com.fjwt.gz.db.entity.AwardAgentEntity;
import com.fjwt.gz.db.entity.AwardGoodsEntity;
import com.fjwt.gz.db.entity.AwardMchEntity;
import com.fjwt.gz.db.entity.AwardSettingEntity;
import com.fjwt.gz.db.vo.AgentDestroyVO;
import com.fjwt.gz.db.vo.AwardGoodsVO;
import com.fjwt.gz.db.vo.ExportAwardVO;
import com.fjwt.gz.service.mapper.AwardGoodsMapper;
import com.fjwt.gz.util.Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.http.util.TextUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 实体奖品信息表 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class AwardGoodsService extends ServiceImpl<AwardGoodsMapper, AwardGoodsEntity> {

    @Autowired
    private AwardAgentService awardAgentService;
    @Autowired
    private AgentInfoService agentInfoService;
    @Autowired
    private ActivityAwardService activityAwardService;
    @Autowired
    private AwardSettingService awardSettingService;
    @Autowired
    private AwardMchService awardMchService;


    /**
     * 获取列表
     * */
    public List<AwardGoodsVO> queryList(AwardGoodsDTO awardGoodsDTO) {
        if (ObjectUtils.isEmpty(awardGoodsDTO) || ObjectUtils.isEmpty(awardGoodsDTO.getAgentNo())){
            throw new BizException("请选择机构!");
        }
        if (ObjectUtils.isNotEmpty(awardGoodsDTO.getAgentNo())) {
            awardGoodsDTO.setAgentNoList(agentInfoService.queryAllSubAgentNo(awardGoodsDTO.getAgentNo()));
            awardGoodsDTO.setAgentNo(null);
        }
        awardGoodsDTO.setState(Constants.AWARD_STATE.ONLINE);
        awardGoodsDTO.setIsConfigActivity(false);
        return baseMapper.selectGoodsList(awardGoodsDTO);
    }

    /**
     * 获取分页列表
     * */
    public IPage<AwardGoodsVO> queryList(IPage iPage, AwardGoodsDTO awardGoodsDTO) {
        if (ObjectUtils.isNotEmpty(awardGoodsDTO.getAgentNo())) {
            awardGoodsDTO.setAgentNoList(agentInfoService.queryAllSubAgentNo(awardGoodsDTO.getAgentNo()));
            awardGoodsDTO.setAgentNo(null);
        }
        IPage<AwardGoodsVO> page = baseMapper.selectGoodsList(iPage, awardGoodsDTO);
        if (ObjectUtils.isNotEmpty(page) && ObjectUtils.isNotEmpty(page.getRecords())) {
            page.getRecords().forEach(item -> {
                AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(item.getAgentNo());
                if (ObjectUtils.isNotEmpty(agentInfo)) {
                    item.setAgentName(agentInfo.getAgentName());
                }
            });
        }
        return page;
    }

    /**
     * 获取详情
     * @param awardGoodsDTO
     */
    public AwardGoodsVO details(AwardGoodsDTO awardGoodsDTO) {
        Long goodsId = awardGoodsDTO.getGoodsId();
        if (goodsId == null) {
            throw new BizException("请求参数异常，请检查！");
        }
        AwardGoodsEntity awardGoodsEntity = baseMapper.selectById(goodsId);
        if (awardGoodsEntity == null) {
            throw new BizException("该记录不存在！");
        }

        // 可核销卡券的商户
        List<AwardMchEntity> awardMchList = awardMchService.queryMchInfoByCouponId(goodsId, Constants.AWARD.GOODS);
        // 分配机构数量
        List<AwardAgentEntity> awardAgentEntityList = awardAgentService.getSavedData(goodsId, Constants.AWARD.GOODS);

        // 实物配置信息
        AwardSettingEntity awardSettingEntity = awardSettingService.getOne(AwardSettingEntity.gw()
                .eq(AwardSettingEntity::getAwardId, awardGoodsEntity.getGoodsId())
                .eq(AwardSettingEntity::getAwardType, Constants.AWARD.GOODS));

        AwardGoodsVO awardGoodsVO = new AwardGoodsVO();
        BeanUtils.copyProperties(awardGoodsEntity, awardGoodsVO);
        awardGoodsVO.setAwardAgentList(awardAgentEntityList);
        awardGoodsVO.setAwardSetting(awardSettingEntity);
        awardGoodsVO.setAwardMchList(awardMchList);
        if (ObjectUtils.isNotEmpty(awardGoodsEntity.getAgentNo())) {
            AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(awardGoodsEntity.getAgentNo());
            if (ObjectUtils.isNotEmpty(agentInfo)) {
                awardGoodsVO.setAgentName(agentInfo.getAgentName());
            }
        }
        return awardGoodsVO;
    }

    /**
     * 新增
     * @param awardGoodsDTO
     */
    public AwardGoodsVO add(AwardGoodsDTO awardGoodsDTO) {
        if (ObjectUtils.isEmpty(awardGoodsDTO.getGoodsName())) {
            throw new BizException("商品名称不能为空，请检查！");
        }
        if (awardGoodsDTO.getState() != null && awardGoodsDTO.getState() != Constants.AWARD_STATE.DRAFT) {
            if (ObjectUtils.isEmpty(awardGoodsDTO.getGoodsImgBanner()) || ObjectUtils.isEmpty(awardGoodsDTO.getGoodsDetail()) || awardGoodsDTO.getGoodsNum() == null
                    || awardGoodsDTO.getGoodsPrice() == null || ObjectUtils.isEmpty(awardGoodsDTO.getAgentNo())|| awardGoodsDTO.getGoodsAmount()==null) {
                throw new BizException("请求参数不全，请检查！");
            }

            AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(awardGoodsDTO.getAgentNo());
            if(agentInfo==null){
                throw new BizException("所选机构不存在，请检查！");
            }else {
                awardGoodsDTO.setAgentNo1(agentInfo.getAgentNo1());
                awardGoodsDTO.setAgentNo2(agentInfo.getAgentNo2());
                awardGoodsDTO.setAgentNo3(agentInfo.getAgentNo3());
                awardGoodsDTO.setAgentNo4(agentInfo.getAgentNo4());
            }
        }

        AwardGoodsEntity awardGoodsEntity = new AwardGoodsEntity();
        BeanUtils.copyProperties(awardGoodsDTO, awardGoodsEntity);

        awardGoodsEntity.setBatchNo(Utils.generateBathNo());//后端生成批次号

        baseMapper.insert(awardGoodsEntity);

        //组装返回参数
        AwardGoodsVO awardGoodsVO = new AwardGoodsVO();
        BeanUtils.copyProperties(awardGoodsEntity, awardGoodsVO);
        return awardGoodsVO;
    }

    /**
     * 修改
     * @param awardGoodsDTO
     */
    public void update(AwardGoodsDTO awardGoodsDTO) {
        Long goodsId = awardGoodsDTO.getGoodsId();
        if (goodsId == null) {
            throw new BizException("请求参数异常，请检查！");
        }
        if (awardGoodsDTO.getState() != null && awardGoodsDTO.getState() != Constants.AWARD_STATE.DRAFT) {
            if (TextUtils.isEmpty(awardGoodsDTO.getGoodsName()) || TextUtils.isEmpty(awardGoodsDTO.getGoodsImgBanner()) || TextUtils.isEmpty(awardGoodsDTO.getGoodsDetail()) || awardGoodsDTO.getGoodsNum() == null
                    || awardGoodsDTO.getGoodsPrice() == null || TextUtils.isEmpty(awardGoodsDTO.getAgentNo())) {
                throw new BizException("请求参数不全，请检查！");
            }
            AgentInfoEntity agentInfo=agentInfoService.getById(awardGoodsDTO.getAgentNo());
            if(agentInfo==null){
                throw new BizException("所选机构不存在，请检查！");
            }else {
                awardGoodsDTO.setAgentNo1(agentInfo.getAgentNo1());
                awardGoodsDTO.setAgentNo2(agentInfo.getAgentNo2());
                awardGoodsDTO.setAgentNo3(agentInfo.getAgentNo3());
                awardGoodsDTO.setAgentNo4(agentInfo.getAgentNo4());
            }
        }
        AwardGoodsEntity awardGoodsEntity = baseMapper.selectById(goodsId);
        if (awardGoodsEntity == null) {
            throw new BizException("该记录不存在！");
        }
        // 非草稿状态下只可增加数量
        if (awardGoodsEntity.getState() != Constants.AWARD_STATE.DRAFT) {
            if (awardGoodsEntity.getGoodsNum() > awardGoodsDTO.getGoodsNum()) {
                throw new BizException("奖品数量不可小于原数量！");
            }
        }
        BeanUtils.copyProperties(awardGoodsDTO, awardGoodsEntity);
        awardGoodsEntity.setGoodsNum(awardGoodsDTO.getGoodsNum());

        awardGoodsEntity.setCreatedAt(null);
        awardGoodsEntity.setCreatedUid(null);
        awardGoodsEntity.setBatchNo(null);
        baseMapper.updateById(awardGoodsEntity);
    }

    /**
     * 更改实物奖品状态
     * @param awardGoodsDTO
     */
    public void updateState(AwardGoodsDTO awardGoodsDTO) {
        Long goodsId = awardGoodsDTO.getGoodsId();
        Integer state = awardGoodsDTO.getState();
        if (goodsId == null || state == null) {
            throw new BizException("请求参数异常，请检查！");
        }
        AwardGoodsEntity entity = baseMapper.selectById(goodsId);
        if (entity == null) {
            throw new BizException("该记录不存在！");
        }
        entity.setState(state);
        baseMapper.updateById(entity);
    }

    /**
     * 删除
     * @param awardGoodsDTO
     */
    @Transactional
    public void delete(AwardGoodsDTO awardGoodsDTO) {
        Long goodsId = awardGoodsDTO.getGoodsId();
        if (goodsId == null) {
            throw new BizException("请求参数异常，请检查！");
        }
        AwardGoodsEntity entity = baseMapper.selectById(goodsId);
        if (entity == null) {
            throw new BizException("该记录不存在！");
        }
        long count = activityAwardService.count(ActivityAwardEntity.gw().eq(ActivityAwardEntity::getAwardId, goodsId).eq(ActivityAwardEntity::getAwardType, Constants.AWARD.GOODS));
        if (count > 0) {
            throw new BizException("该奖品已配置活动，不能删除！");
        }
        baseMapper.deleteById(goodsId);
        // 删除奖品配置信息
        awardSettingService.remove(AwardSettingEntity.gw().eq(AwardSettingEntity::getAwardId, goodsId)
                .eq(AwardSettingEntity::getAwardType, Constants.AWARD.COUPON));
    }

    /**
     * 获取可核销机构列表
     * @param iPage
     * @param goodsId
     * @param radius
     */
    public IPage<AgentDestroyVO> getAgentDestroyList(IPage iPage, PointDTO location, Long goodsId, String radius) {
        AwardGoodsEntity awardGoodsEntity = baseMapper.selectById(goodsId);
        AwardSettingEntity awardSettingEntity = awardSettingService.getOne(AwardSettingEntity.gw().eq(AwardSettingEntity::getAwardId, goodsId)
                .eq(AwardSettingEntity::getAwardType, Constants.AWARD.GOODS));
        // 是否限制可派发/激活机构（0否，1是
        if (awardSettingEntity.getIsAllocation().equals(0)) {
            List<String> agentNos = agentInfoService.queryAllSubAgentNo(awardGoodsEntity.getAgentNo());
            if (agentNos.isEmpty()) {
                return null;
            }
            return agentInfoService.getNearAgentList(iPage, location, radius, agentNos);
        }
        return agentInfoService.getAgentDestroyList(iPage,location, goodsId, radius);
    }

    public IPage<ExportAwardVO> activityGoodsDetail(IPage iPage , ActivityAwardDTO activityAwardDTO) {
        return baseMapper.activityGoodsDetail(iPage, activityAwardDTO);
    }
    public List<ExportAwardVO> activityGoodsDetail(ActivityAwardDTO activityAwardDTO) {
        return baseMapper.activityGoodsDetail(activityAwardDTO);
    }
}
